<?php

require_once 'Base/Exception.php';

class Base_Db_Exception extends Base_Exception
{
    public function translateError()
    {
        if (Zend_Registry::isRegistered('Zend_Translate')) {
			Zend_Registry::get('Zend_Translate')->addTranslation(
				array(
					'adapter'	=> 'gettext',
					'content'	=> MODULES_PATH .'/../private/language/exception/pdo/zh_CN.mo',
					'locale'	=> 'zh_CN',
				)
			);
		}
        
		$sqlStateFile = dirname(__FILE__) .'/Data/state.xml';
		if (!is_file($sqlStateFile )) {
            throw $this->getPrevious();
		}

		$sqlErrorConfig = new Zend_Config_Xml($sqlStateFile, 'errors');
		$errorArray = $sqlErrorConfig->toArray();
		//create index
		if (!isset($errorArray['error'][0])) {
			$errorArray['error'] = array($errorArray['error']);
		}
		foreach ($errorArray['error'] as $error) {
            $errorIndexs[$error['key']] = $error['val'];
        }
        
        //match ident
        if (isset($errorIndexs[$this->getCode()])) {
            $keyExp = preg_replace("'%(.+?)%'", "(?<\\1>.+?)", $errorIndexs[$this->getCode()]);
            if (preg_match("/^".$keyExp."$/", $this->getMessage(), $messageVariables)) {
                $message = Zend_Registry::get('Zend_Translate')
                            ->translate('ERROR['.$this->getCode().']');
                
                foreach ($messageVariables as $field=> $value) {
                    $message = str_replace("%$field%", $value, $message);
                }

                return array(
                    'key' => $messageVariables['key'],
                    'message' => $message
                );
            }
        }
        
		throw $this->getPrevious();
    }
}